﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.WeiXin;
using Atmk.WaterMeter.MIS.Controllers.Pay.Base;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers.Pay
{
    /// <summary>
    /// 微信小程序业务逻辑接口
    /// </summary>
    [Wx_Authorize]
    public class Wx_SmallRoutine_BusinessController : BaseApiController
    {
        private static ILogger<Wx_SmallRoutine_BusinessController> _Logger;
        private readonly IWxAccountLogic _wxAccountLogic;
        private readonly IWxOtherLogic _wxOtherLogic;

        /// <inheritdoc />
        public Wx_SmallRoutine_BusinessController(
            IWxAccountLogic wxAccountLogic,
            IWxOtherLogic wxOtherLogic,
            ILogger<Wx_SmallRoutine_BusinessController> logger
        )
        {
            _wxAccountLogic = wxAccountLogic;
            _wxOtherLogic = wxOtherLogic;
            _Logger = logger;
        }

        /// <summary>
        /// 绑定用户与水表关系
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/pay/wx/binding")]
        public async Task<IActionResult> BindOpenId([FromBody] dynamic obj)
        {
            try
            {
                string meterNumber = Convert.ToString(obj.meterNumber);
                string openid = Convert.ToString(obj.openid);
                var success = await _wxAccountLogic.AddAccount(openid, meterNumber, out var name, out var houseNumber, out var balance);
                if (!success) return Ok(new { errcode = 1, msg = "绑定失败" });
                var account = new WxAccountVm
                {
                    openid = openid,
                    Isbind = 0,
                    ownerName = name,
                    meterNumber = meterNumber,
                    houseNumber = houseNumber,
                    balance = decimal.ToInt32(balance * 100)
                };
                return Ok(new { errcode = 0, msg = "绑定成功", data = new { account } });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"绑定失败:{e.Message}" });
            }
        }

        /// <summary>
        /// 绑定用户与水表关系（新版）
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/pay/wx/binding2")]
        public IActionResult BindOpenId2([FromBody] dynamic obj)
        {
            try
            {
                string meterNumber = obj.meterNumber;
                string openid = obj.openid;

                var owner = _wxAccountLogic.GetOwner(openid, meterNumber, out decimal balance);
                if (owner == null) return Ok(new { errcode = 1, msg = "绑定失败 owner is null" });

                var meters = _wxAccountLogic.GetMeters(owner.Id);
                if (meters == null) return Ok(new { errcode = 1, msg = "绑定失败 meters is null" });

                var success = _wxAccountLogic.AddAccount2(openid, meters.First(m => m.MeterNumber == meterNumber), owner);
                if (!success) return Ok(new { errcode = 1, msg = "绑定失败" });

                var account = meters.Select(m => new WxAccountVm
                {
                    openid = openid,
                    Isbind = 0,
                    ownerName = owner.Name,
                    meterNumber = m.MeterNumber,
                    houseNumber = owner.HouseNumber,
                    balance = decimal.ToInt32(balance * 100)
                });
                //var account = new WxAccountVm
                //{
                //    openid = openid,
                //    Isbind = 0,
                //    ownerName = owner.Name,
                //    meterNumber = meterNumber,
                //    houseNumber = owner.HouseNumber;
                //    balance = decimal.ToInt32(balance * 100)
                //};
                return Ok(new { errcode = 0, msg = "绑定成功", data = new { account } });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"绑定失败:{e.Message}" });
            }
        }
        /// <summary>
        /// 解除用户与水表绑定
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut("/api/{X-Version}/pay/wx/unbinding")]
        public async Task<IActionResult> UnBindOpenId([FromBody] dynamic obj)
        {
            try
            {
                string meterNumber = Convert.ToString(obj.meterNumber);
                string openid = Convert.ToString(obj.openid);
                var success = await _wxAccountLogic.LogoutAccount(openid, meterNumber);
                return success
                    ? Ok(new { errcode = 0, msg = "解绑成功" })
                    : Ok(new { errcode = 1, msg = "解绑失败" });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"解绑失败:{e.Message}" });
            }
        }

        /// <summary>
        /// 查询该用户关联的水表账户余额
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="meterNumber"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/pay/wx/balance")]
        public async Task<IActionResult> Balance(string openid, string meterNumber)
        {
            try
            {
                var success = await _wxAccountLogic.SelectAccount(openid, out var mNumber, out var houseNumber,
                    out var balance, meterNumber);
                return success
                    ? Ok(new { errcode = 0, msg = "查询成功", data = new { balance = decimal.ToInt32(balance * 100) } })
                    : Ok(new { errcode = 1, msg = "查询失败" });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"查询失败:{e.Message}" });
            }
        }

        /// <summary>
        /// 查询微信小程序常见问题解答
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/pay/wx/questions")]
        public async Task<IActionResult> Questions(string openid)
        {
            try
            {
                var recordlist =
                    await _wxOtherLogic.SelectWxQuestions(openid);
                var questions = recordlist.Select(r => new { title = r.Key, answer = r.Value }).ToList();
                return Ok(new { errcode = 0, msg = "查询成功", data = new { questions } });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"查询成功:{e.Message}" });
            }
        }
    }
}